package com.geeklan.base.network;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UdpReceiver {

    public interface OnResultListener {
        void onResult(String message);
    }

    public static void listenForResult(int port, OnResultListener listener) {
        new Thread(() -> {
            try {
                DatagramSocket socket = new DatagramSocket(port);
                byte[] buffer = new byte[1024];
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

                while (true) {
                    socket.receive(packet);
                    String message = new String(packet.getData(), 0, packet.getLength());
                    listener.onResult(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}

